package com.javenwong.android.engine;

import java.lang.reflect.Method;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameCanvas extends SurfaceView implements Runnable, SurfaceHolder.Callback {

	public static GameCanvas gameCanvas;

	// 将当前屏幕宽、高 设为私有，防止其它类使用
	// 请参见ImageManager中的 STANDARD_WIDTH,STANDARD_HEIGHT
	private static int SW;
	private static int SH;

	public static Boolean pauss = false;
	private boolean runs;
	private SurfaceHolder holder;
	private Canvas canvas;

	private CFPSMaker fpsMaker = new CFPSMaker();
	public boolean showFPS;

	 private static Bitmap currentBitmap;
	 private static Bitmap doubleBuffered;
	 private static Canvas doubleCanvas;

	private View view;

	public View getView() {
		return view;
	}

	/**
	 * 主线程 休眠时间
	 */
	public static short SLEEP_TIME = 40;

	/**
	 * 主线程循环开始时间
	 */
	private long startTime;

	public static boolean pause = false;
	/**
	 * 主线程循环结束时间 与 开始的时间差
	 */
	public static long timeCha = SLEEP_TIME;

	public GameCanvas(Context context) {
		this(context, null, 0);
	}

	public GameCanvas(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public GameCanvas(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		gameCanvas = this;
		View.canvas = this;
		setClickable(true);

		holder = getHolder();
		holder.addCallback(this);

	}

	@Override
	public void run() {
		while (runs) {
			startTime = System.currentTimeMillis(); // 开始时间

			canvas = holder.lockCanvas();
			if (!(ImageManager.SCALE_HEIGHT == 1 && ImageManager.SCALE_WIDTH == 1)) {
				canvas.setMatrix(ImageManager.MATRIX);
			}

			canvas.drawColor(Color.BLACK);

			// 绘制到 缓冲 Canvas
			if (view != null) {
				view.doLogic();
				view.doDraw(canvas);
			}

			if (showFPS) {
				Graphics.PAINT.setColor(Color.BLACK);
				Graphics.PAINT.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
				Graphics.PAINT.setTextSize(30);
				// canvas.drawText(1000 / timeCha + " fps", 100, 100,
				// Graphics.PAINT);

				canvas.drawText(fpsMaker.makeFPS() + " fps", 100, 100, Graphics.PAINT);
			}

			// 将缓冲Bitmap 画到 Canvas

//			 canvas.drawBitmap(ImageManager.getBitmap(doubleBuffered), 0, 0,
//			 Graphics.PAINT);

			// if (currentBitmap!=null){
			// currentBitmap.recycle();
			// System.gc();
			// }

//			 currentBitmap = ImageManager.getBitmap(doubleBuffered);

			// canvas.drawBitmap(currentBitmap, 0, 0, Graphics.PAINT);

			holder.unlockCanvasAndPost(canvas);

			timeCha = System.currentTimeMillis() - startTime;

			if (timeCha < SLEEP_TIME) {
				try {
					Thread.sleep(SLEEP_TIME - timeCha);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			timeCha = System.currentTimeMillis() - startTime;
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		SH = getHeight();
		SW = getWidth();

		// 计算图片缩放比例
		ImageManager.jsScale(SW, SH);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// 获取屏幕宽、高
		SH = getHeight();
		SW = getWidth();

		// 计算图片缩放比例
		ImageManager.jsScale(SW, SH);

		// 创建缓冲Bitmap ，以便缩放
		// doubleBuffered = Bitmap.createBitmap(ImageManager.STANDARD_WIDTH,
		// ImageManager.STANDARD_HEIGHT,
		// Bitmap.Config.RGB_565);
		// doubleCanvas = new Canvas(doubleBuffered);

		if (!runs) {
			runs = true;
			new Thread(this).start();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		runs = false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		float x = event.getX() / ImageManager.SCALE_WIDTH - ImageManager.translateX;
		float y = event.getY() / ImageManager.SCALE_HEIGHT - ImageManager.translateY;

		// System.out.println("x= " + x + "   y= " + y + "  x= " + (int) x +
		// "   y= " + (int) y);
		if (view != null) {

			view.doTouchEvent(event, x, y, (int) x, (int) y);

			if (GameActivity.SDK16) {

				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					view.doTouchDownEvent(event, x, y, (int) x, (int) y);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					view.doTouchUpEvent(event, x, y, (int) x, (int) y);
				} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
					view.doTouchMoveEvent(event, x, y, (int) x, (int) y);
				}

			} else {

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					view.doTouchDownEvent(event, x, y, (int) x, (int) y);
					break;
				case 5:
					x = getX(event, 0) / ImageManager.SCALE_WIDTH - ImageManager.translateX;
					y = getY(event, 0) / ImageManager.SCALE_HEIGHT - ImageManager.translateY;
					view.doTouchDownEvent(event, x, y, (int) x, (int) y);
					break;
				case 261:
					x = getX(event, 1) / ImageManager.SCALE_WIDTH - ImageManager.translateX;
					y = getY(event, 1) / ImageManager.SCALE_HEIGHT - ImageManager.translateY;
					view.doTouchDownEvent(event, x, y, (int) x, (int) y);
					break;
				case 517:
					x = getX(event, 2) / ImageManager.SCALE_WIDTH - ImageManager.translateX;
					y = getY(event, 2) / ImageManager.SCALE_HEIGHT - ImageManager.translateY;
					view.doTouchDownEvent(event, x, y, (int) x, (int) y);
					break;
				case MotionEvent.ACTION_UP:
					view.doTouchUpEvent(event, x, y, (int) x, (int) y);
					break;
				case 6:
					x = getX(event, 0) / ImageManager.SCALE_WIDTH - ImageManager.translateX;
					y = getY(event, 0) / ImageManager.SCALE_HEIGHT - ImageManager.translateY;
					view.doTouchUpEvent(event, x, y, (int) x, (int) y);
					break;
				case 262:
					x = getX(event, 1) / ImageManager.SCALE_WIDTH - ImageManager.translateX;
					y = getY(event, 1) / ImageManager.SCALE_HEIGHT - ImageManager.translateY;
					view.doTouchUpEvent(event, x, y, (int) x, (int) y);
					break;
				case 518:
					x = getX(event, 2) / ImageManager.SCALE_WIDTH - ImageManager.translateX;
					y = getY(event, 2) / ImageManager.SCALE_HEIGHT - ImageManager.translateY;
					view.doTouchUpEvent(event, x, y, (int) x, (int) y);
					break;
				case MotionEvent.ACTION_MOVE:
					view.doTouchMoveEvent(event, x, y, (int) x, (int) y);
					break;
				}

			}
		}

		return super.onTouchEvent(event);
	}

	private float getX(MotionEvent event, int pointer) {
		float x = 0;
		try {
			Method method = MotionEvent.class.getMethod("getX", new Class[] { int.class });
			if (method != null) {
				Object rs = method.invoke(event, new Object[] { pointer });
				if (rs instanceof Number) {
					x = ((Number) rs).floatValue();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return x;
	}

	private float getY(MotionEvent event, int pointer) {
		float y = 0;
		try {
			Method method = MotionEvent.class.getMethod("getY", new Class[] { int.class });
			if (method != null) {
				Object rs = method.invoke(event, new Object[] { pointer });
				if (rs instanceof Number) {
					y = ((Number) rs).floatValue();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return y;
	}

	/**
	 * (清除当前显示的view) 清除子类的上一级
	 */
	public final void closeTopView() {
		View ve = view;
		View parent = null;
		while (ve.getChildView() != null) {
			parent = ve;
			ve = ve.getChildView();
		}
		if (parent != null) {
			parent.clearChildView();
		}
	}

	/**
	 * 获取最顶层的View、子View
	 * 
	 * @return View
	 */
	public View getTopView() {
		View ve = view;
		View parent = null;
		while (ve.getChildView() != null) {
			parent = ve;
			ve = ve.getChildView();
		}
		if (parent != null) {
			return parent.getChildView();
		}

		return view;
	}

	/**
	 * 添加子视图
	 * 
	 * @param childView
	 */
	public final void appendView(View childView) {
		if (view == null) {
			setView(childView);
		} else {
			view.appendView(childView);
		}
	}

	/**
	 * 重新设置当前视图
	 */
	public final void setView(View view) {
		View temp = this.view;

		view.setParentView(null);
		this.view = view;

		if (temp != null) {
			temp.doDestroy();
		}

		// KeyManager.setTopView(view);
	}

}
